package bookStore.eBook.android;
import bookStore.eBook.android.bookKEEPFORGUID.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Paint.Align;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ViewStub;

public class ReadingActivity extends Activity {
	
	public static final String TAG = "eBook:Bright";
	private final String PREFERENCES_NAME="ReadingConfig";
	
	/** Called when the activity is first created. */
	private PageWidget mPageWidget;
	private SeekBar mSeekBar;
	private boolean mIsSeekBarVisible;
	private View mViewToolBar;
	
	private boolean mIsMoved;
	private boolean mIsMovedtoNext;
	
	Bitmap mCurPageBitmap, mNextPageBitmap;
	Canvas mCurPageCanvas, mNextPageCanvas;
	BookPageFactory pagefactory;
	
	private DisplayMetrics dm;
	private File mBookFile;
	private int mChapterID;
	private String mTitle = "";
	PointF mTouchDown = new PointF();
	
	// use this handler to load "loading" page
	private Handler handler;
	
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		
		if(mBookFile!=null && mBookFile.exists())
		{
			mBookFile.delete();
		}
		
	}
	
	@Override
	public void onStop()
	{
		super.onStop();
		
		SharedPreferences MyPreferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = MyPreferences.edit();
		//editor.putInt("ChapterID", mChapterID);
		editor.putInt("BeginPage", pagefactory.getCurrentPage());
		//editor.putString("ChapterName", mTitle);
		editor.commit();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		

		setContentView(R.layout.main);
		
		mTouchDown.x=0f;
		mTouchDown.y=0f;
		
		//get the size of screen
		dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);		
		int width = dm.widthPixels ;
		int height = dm.heightPixels ;
		
		//mPageWidget = new PageWidget(this);
		mPageWidget = (PageWidget)findViewById(R.id.viewMain);	
		mPageWidget.setScreen(width, height);
		
		
		mViewToolBar = findViewById(R.id.includeToolbar);
		mViewToolBar.setVisibility(View.INVISIBLE);
		
		mIsSeekBarVisible = false;
		

		mCurPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		mNextPageBitmap = Bitmap
				.createBitmap(width, height, Bitmap.Config.ARGB_8888);

		mCurPageCanvas = new Canvas(mCurPageBitmap);
		mNextPageCanvas = new Canvas(mNextPageBitmap);
		pagefactory = new BookPageFactory(width, height);
		
		
		// Set the loading page
		final Bitmap bg = BitmapFactory.decodeResource(this.getResources(), R.drawable.shelf_bkg);
		if (bg == null)
			mCurPageCanvas.drawColor(Color.argb(0xff, 255, 230, 140));
		else
			mCurPageCanvas.drawBitmap(bg, 0, 0, null);
		int fontSize = 16 * (width/240);// calculate real size
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setTextAlign(Align.LEFT);
		paint.setTextSize(fontSize);
		paint.setColor(Color.argb(0xff, 128, 10, 10));
		mCurPageCanvas.drawText(this.getResources().getString(R.string.loading), 8, 6+fontSize, paint);
		mPageWidget.setBitmaps(mCurPageBitmap, mCurPageBitmap);
		
		handler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				if(msg.what == 1)
				{
					mPageWidget.invalidate();
				}
			}
        };
		
		
		
		Runnable runnable = new Runnable()
		{
			public void run()
			{
				pagefactory.setBgBitmap(bg);
				
				// continue reading or a new chapter
				int beginPage = 0;
				Intent intent = ReadingActivity.this.getIntent();
				Bundle bundle=intent.getExtras();
				SharedPreferences preferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
				if(bundle.getBoolean("isContinue") && preferences.contains("ChapterID"))
				{
					mChapterID = preferences.getInt("ChapterID", bundle.getInt("ChapterID"));
					beginPage = preferences.getInt("BeginPage",0);
					mTitle = preferences.getString("ChapterName", "");
				}
				else
				{
					mChapterID = bundle.getInt("ChapterID");
					mTitle = bundle.getString("ChapterName");

					SharedPreferences.Editor editor = preferences.edit();
					editor.putInt("ChapterID", mChapterID);
					editor.putInt("BeginPage", 0);
					editor.putString("ChapterName", mTitle);
					editor.commit();
				}
				
				TextView tvTitle = (TextView)findViewById(R.id.textViewTitle);
				tvTitle.setText(mTitle);

				try {
					
					InputStream is = ReadingActivity.this.getResources().openRawResource(mChapterID);
		            File bookDir = ReadingActivity.this.getDir("book", Context.MODE_PRIVATE);
		            mBookFile = new File(bookDir, mChapterID + ".txt");
		            FileOutputStream os = new FileOutputStream(mBookFile);

		            byte[] buffer = new byte[4096];
		            int bytesRead;
		            while ((bytesRead = is.read(buffer)) != -1) {
		                os.write(buffer, 0, bytesRead);
		            }
		            is.close();
		            os.close();
		            
		            
					String path = mBookFile.getAbsolutePath();
					File filePath= new File(path);
					Log.e(TAG, path);
					if(!filePath.exists())
					{
						throw new IOException("cannot find the book!!!!!!!");
					}
					Log.e(TAG, path+ " exists!!!!!!");
					
					pagefactory.openbook(path);
					
					Log.e(TAG, "opened!!!!");
					
					pagefactory.gotoPage(beginPage);
					
					pagefactory.onDraw(mCurPageCanvas);
					
					Log.e(TAG, "Drawed!!!!!");
				} catch (IOException e1) {
					Toast.makeText(ReadingActivity.this, "Cannot find the book!",
							Toast.LENGTH_LONG).show();
				}
				
				
				
				
				mSeekBar= (SeekBar)findViewById(R.id.seekBar1);
				final int pageNumber = pagefactory.getPageNumber();
				if(pageNumber<=1)
					mSeekBar.setMax(1);
				else
					mSeekBar.setMax(pageNumber-1);
				mSeekBar.setProgress(beginPage);
				
				final TextView tv = (TextView)findViewById(R.id.textView2);
				tv.setText(++beginPage + "/" + pageNumber);
				
				mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

					public void onProgressChanged(SeekBar seekBar, int progress,
							boolean fromUser) {
						
						if(fromUser)
						{
							//pagefactory.gotoPage(progress);
							pagefactory.onDrawPage(mCurPageCanvas, progress);
							mPageWidget.setBitmaps(mCurPageBitmap, mCurPageBitmap);
							mPageWidget.postInvalidate();
							
							tv.setText(++progress + "/" + pageNumber);
						}
						
					}

					public void onStartTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
						
					}

					public void onStopTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
						pagefactory.gotoPage(seekBar.getProgress());
						pagefactory.onDraw(mCurPageCanvas);
						mPageWidget.setBitmaps(mCurPageBitmap, mCurPageBitmap);
						mPageWidget.postInvalidate();
					}
					
				});
				

				mPageWidget.setBitmaps(mCurPageBitmap, mCurPageBitmap);
				
				mPageWidget.setOnTouchListener(new OnTouchListener() {
					
					//@Override
					public boolean onTouch(View v, MotionEvent e) {
						// TODO Auto-generated method stub
						
						boolean ret = true;
						
						try
						{
							if (v == mPageWidget) {
								if (e.getAction() == MotionEvent.ACTION_DOWN){
									
									// don't handler any motion here when click on the toolbar
									if(mIsSeekBarVisible && e.getY() <= mViewToolBar.getHeight())
									{
										return false;
									}
									
									mPageWidget.abortAnimation();
									mPageWidget.calcCornerXY(e.getX(), e.getY());
									
									//record the touch point
									mTouchDown.x=e.getX();
									mTouchDown.y=e.getY();
									
									mIsMoved = false;
									
									ret = mPageWidget.doTouchEvent(e);
								}
								
								if (e.getAction() == MotionEvent.ACTION_UP){
									if(!mIsMoved)
									{
										if(mIsSeekBarVisible)
											mViewToolBar.setVisibility(View.INVISIBLE);
										else
											mViewToolBar.setVisibility(View.VISIBLE);
										
										mIsSeekBarVisible = !mIsSeekBarVisible;
										
									}

									ret = mPageWidget.doTouchEvent(e);
									
								    if(mIsMoved)
								    {
										if(!mPageWidget.isAbortLastFlip())
										{
											if (!mIsMovedtoNext)
												pagefactory.prePage();
											else
												pagefactory.nextPage();
										}
								    }
								    
								    int page = pagefactory.getCurrentPage();
									mSeekBar.setProgress(page);
									tv.setText(++page + "/" + pageNumber);
									mIsMoved = false;
								}
						
								if (e.getAction() == MotionEvent.ACTION_MOVE) {
									
									if(!mIsMoved && Math.hypot((mTouchDown.x - e.getX()),(mTouchDown.y - e.getY())) > 6)
									{
										
										if (mPageWidget.DragToRight()) {
											if(pagefactory.isfirstPage())
											{
												return false;
											}
											pagefactory.onDrawPrePage(mNextPageCanvas);
											mIsMovedtoNext = false;
										} else 
										{
											if(pagefactory.islastPage())
											{
												return false;
											}
											pagefactory.onDrawNextPage(mNextPageCanvas);
											mIsMovedtoNext = true;
										}
										
										mIsMoved = true;
										mPageWidget.setMoved(mIsMoved);
										pagefactory.onDraw(mCurPageCanvas);
										mPageWidget.setBitmaps(mCurPageBitmap, mNextPageBitmap);

									}
									
									ret = mPageWidget.doTouchEvent(e);
								}

								return ret;
							
							}
						}
						catch(Exception ex)
						{
							ex.printStackTrace();
						}


						return true;
					}

				});
				
				
				Button buttonContent = (Button)findViewById(R.id.buttonContent);
				buttonContent.setOnClickListener(new OnClickListener(){
					
					public void onClick(View v){
					     
						//Intent intent = new Intent();
						//intent.setClass(ReadingActivity.this, EBookEntryActivity.class);
						//startActivityForResult(intent, 1);
						ReadingActivity.this.finish();
					 }

				});
				
				Button buttonNext = (Button)findViewById(R.id.buttonNext);
				buttonNext.setOnClickListener(new OnClickListener(){
					
					public void onClick(View v){
					    
						SharedPreferences preferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
						
						String curChapterName = preferences.getString("ChapterName", "");
						ChapterManager cm = ChapterManager.getChapterManager();
						if(cm.isLastChapter(curChapterName))
						{
							Toast.makeText(getApplicationContext(), R.string.lastChapter, Toast.LENGTH_LONG).show();
							return;
						}
						
						String nextChapterName = cm.getNextChapterName(curChapterName);
						int nextChapterID = cm.getChapterResourceID(nextChapterName);

						Intent intent = new Intent();
						intent.setClass(ReadingActivity.this, ReadingActivity.class);
						
				        // pass charpter and page number to ReadingActivity        
				        Bundle bundle=new Bundle();
				        bundle.putString("ChapterName",nextChapterName);
				        bundle.putInt("ChapterID",nextChapterID);
				        intent.putExtras(bundle);
				        
						startActivity(intent);
						ReadingActivity.this.finish();
						
					 }

				});
				
				handler.sendEmptyMessage(1);
			}

        };
        Thread thread = new Thread(runnable);
        thread.start();
		


	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		if(mIsSeekBarVisible)
			mViewToolBar.setVisibility(View.INVISIBLE);
		else
			mViewToolBar.setVisibility(View.VISIBLE);
		
		mIsSeekBarVisible = !mIsSeekBarVisible;
		
		return false;
	}
}